package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.utils.Constants;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/role")
public class SysRoleController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    SysRoleService sysRoleService;

    //跳转到role/list.jsp页面
    @GetMapping("/list")
    public String list(Model  model) {
        try {
            List<SysRole> roleList = sysRoleService.findAll();
            model.addAttribute("list", roleList);
            return "role/list";
        } catch (Exception e) {
            logger.error("SysRoleController中的list方法执行错误", e);
            throw new RuntimeException(e);
        }
    }


    // 判断账号是否存在
    @ResponseBody
    @GetMapping("/codeExist")
    public String codeExist(@RequestParam("code") String code) {
        logger.info("检查角色编号是否存在：{}", code);
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(code)){
            resultMap.put("exist", 0);
        }else{
            try{
                SysRole sysRole = sysRoleService.bian(code);
                if (sysRole != null){
                    //用户名已存在
                    resultMap.put("exist", 1);
                }else{
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                resultMap.put("error", "验证账号时发生错误");
                logger.error("验证账号出错", e);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    //跳转到sava.jsp页面
    @GetMapping("/save")
    public String toSave(Model model) {
        List<SysRole> roleList = null;
        try {
            roleList = sysRoleService.findAll();
            model.addAttribute("roleList", roleList);
            model.addAttribute("SysRole", new SysRole());
        }catch (Exception e){
            logger.error("SysUserController中的toSave方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    //查询用户信息
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model){
        try{
            SysRole sysRole = sysRoleService.getById(id);
            model.addAttribute("sysRole", sysRole);
        } catch (Exception e) {
            logger.error("SysRoleController中的view方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "role/list";

    }

    //删除用户
    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Map<String, Object> del(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        try{
            boolean ok = sysRoleService.delete(id);
            if (ok){
                result.put("code", 200);
                result.put("message", "删除成功");
            }else{
                result.put("code", 500);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("error", "删除角色时发生错误");
            result.put("code", 500);
            logger.error("删除角色出错", e);
        }
        return result;
    }

    //查询用户信息并跳转到修改页面
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        SysRole sysRole = null;
        List <SysRole> roleList = null;
        try {
            sysRole = sysRoleService.getById(id);
            roleList = sysRoleService.findAll();
            model.addAttribute("roleList", roleList);
            model.addAttribute("sysRole", sysRole);
        } catch (Exception e) {
            logger.error("SysRoleController中的edit方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    //新增角色
    @PostMapping("/save")
    public String doSave(@ModelAttribute SysRole sysRole) {
        try {
            if (sysRole.getId() == null) {
                // 新增角色：设置创建时间
                sysRole.setCreatedTime(new Date());
            }
            // 无论是新增还是修改，都更新修改时间
            sysRole.setUpdatedTime(new Date());

            // 直接保存传入的sysRole对象（而非new的空对象）
            boolean ok = sysRoleService.upInsert(sysRole);

            if (ok) {
                return redirect("/main/role/list");
            }
        } catch (Exception e) {
            logger.error("保存角色失败", e);
        }
        return "role/save";
    }
}
